import { Tabs, Tag } from 'antd'
import { useState, useEffect, useMemo } from 'preact/hooks'
import type { Endpoint } from '../types/Endpoint'
import { methodColorMap } from '../utils/Common'
import Index from '../components/Index'
import Method from './Method';
export default function ApiExplorer({ endpoint, path, segment }: { endpoint: Endpoint | undefined, path: string, segment: string }) {
    if (!endpoint) {
        return <div>No API endpoint available</div>;
    }

    const [activeKey, setActiveKey] = useState<string>('index');
    useEffect(() => {
        setActiveKey('index');
    }, [path])

    const safeEndpoint = useMemo(() => endpoint || {
        paths: {},
        info: {},
        servers: [],
        externalDocs: undefined,
        tags: []
    }, [endpoint])

    const { pathsMap, info, servers, externalDocs, tags } = useMemo(() => ({
        pathsMap: new Map(Object.entries(safeEndpoint.paths)),
        info: safeEndpoint.info || {},
        servers: safeEndpoint.servers || [],
        externalDocs: safeEndpoint.externalDocs,
        tags: safeEndpoint.tags || []
    }), [safeEndpoint])

    const methods = useMemo(() => {
        const pathMethods = pathsMap.get(path)
        return pathMethods && Object.keys(pathMethods).length ? pathMethods : null
    }, [path, pathsMap])

    const tabItems = useMemo(() => {
        const defaultItem = {
            key: 'index',
            label: <Tag color="#999">API INFO</Tag>,
            children: <><Index info={info} servers={servers} external={externalDocs} tags={tags} segment={segment} /></>
        }
        if (!methods || !Object.keys(methods).length) return [defaultItem]
        try {
            return [defaultItem, ...Object.entries(Object.entries(methods || {})[0][1])
                .map(([method, detail]) => ({
                    key: method,
                    label: (
                        <Tag color={
                            methodColorMap(method)
                        }>
                            {method.toUpperCase()}
                        </Tag>
                    ),
                    children: (
                        <Method detail={detail} segment={segment} />
                    )
                }))]
        } catch (error) {
            console.error('Error processing methods:', error);
        }

    }, [methods, info, servers, externalDocs, tags, segment])

    return (
        <>
            <Tabs type="line" activeKey={activeKey} onChange={setActiveKey} animated items={tabItems} />
        </>

    )
}
